<template>
  <div class="user">
    <basic-container>
      <avue-crud
        :option="option"
        ref="crud"
        v-model="form"
        :page="page"
        :simple-page="true"
        @size-change="sizeChange"
        :upload-before="uploadImgBefore"
        :upload-exceed="uploadExceed"
        @current-change="currentChange"
        :table-loading="listLoading"
        @selection-change="selectionChange"
        @search-change="handleFilter"
        @refresh-change="resetHandleFilter"
        @row-update="update"
        @search-reset="resetHandleFilter"
        @row-save="create"
        :before-open="handleOpenBefore"
        :data="list"
      >
        <template slot="menuLeft">
          <el-button
            class="filter-item"
            @click="$refs.crud.rowAdd()"
            type="primary"
            icon="el-icon-edit"
            >添加人物
          </el-button>
          <el-upload
            style="display: inline-block"
            :headers="Authorization"
            :showFileList="false"
            :on-success="uploadSuccess"
            :action="uploadUrl"
          >
            <el-button type="primary" icon="el-icon-upload2">
              批量上传人物
            </el-button>
          </el-upload>
          <el-button
            class="filter-item"
            @click="showMany"
            type="primary"
            :disabled="!selIds.length"
            icon="el-icon-edit"
            >批量展示
          </el-button>
        </template>

        <template slot="is_vip" slot-scope="scope">
          <el-switch
            :value="Boolean(scope.row.is_vip === 0)"
            @change="changeFlagVip(scope.row.is_vip, scope.row.id)"
            active-color="#ff4949"
            inactive-color="#13ce66"
          >
          </el-switch>
        </template>

        <template slot="tag" slot-scope="scope">
          <div v-if="scope.row.tag">
            <span v-for="(item,i) in scope.row.tag.split(',')" :key="i" class="tagBg">
              <span v-for="(tag, j) in tags" :key="j">
                <span v-if="tag.id == item">{{tag.name}}</span> 
              </span>
            </span>
          </div>
          
        </template>

        <template slot="dated_time" slot-scope="scope">
          <span>
            {{scope.row.dated_time | compareTime}}
          </span>
        </template>
        <template slot="show" slot-scope="scope">
          <el-switch
            :value="Boolean(scope.row.show === 0)"
            @change="changeFlagShow(scope.row.show, scope.row.id)"
            active-color="#ff4949"
            inactive-color="#13ce66"
          >
          </el-switch>
        </template>

        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, scope.index)"
            >编辑
          </el-button>
          <el-button
            type="text"
            icon="el-icon-view"
            @click="handleview(scope.row, scope.index)"
            >查看详情
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="deletes(scope.row, scope.index)"
            >删除
          </el-button>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchList,
  putFigure,
  deleteFigure,
  updateFigure,
  figureShowMulti
} from "@/api/admin/figure";

import {fetchTagsAll} from "@/api/admin/tags";

import { listOption } from "@/const/crud/admin/figure";
import { mapGetters } from "vuex";
import moment from "moment";

export default {
  name: "table_user",
  data() {
    return {
      option: listOption,
      params: {},
      queryList: {},
      Authorization: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false //是否倒序
      },
      list: [],
      listLoading: true,
      role: [],
      form: {},
      selIds: [],
      uploadUrl: ''
    };
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  filters: {
    compareTime: function (value) {
      return moment(value).isBefore(moment())?'已到期':value
    }
  },
  created() {
    this.getList(this.page, {});
    this.getTags()
    this.uploadUrl = process.env.VUE_APP_BASE_API + "/admin/upload/figureUpload";
    // this.sys_user_add = this.permissions["sys_user_add"];
    // this.sys_user_edit = this.permissions["sys_user_edit"];
    // this.sys_user_del = this.permissions["sys_user_del"];
  },
  methods: {
    getTags(){
      fetchTagsAll().then(res=>{
        this.tags = res.data.data
      })
    },
    getList(page, params) {
      this.listLoading = true;
      fetchList(
        Object.assign(
          {
            page: page.currentPage,
            size: page.pageSize
          },
          params || this.params
        )
      ).then(response => {
        this.list = response.data.data.data;
        this.page.total = response.data.data.count || '0';
        for (const item of  this.list) {
          if(item.dated_time === '0000-00-00'){
            item.dated_time = ''
          }
          if(item.city){
            item.city = item.city.split(',')
          }
        }
        this.listLoading = false;
      });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList(this.page);
    },
    currentChange(current) {
      this.page.currentPage = current;
      this.getList(this.page);
    },
    handleFilter(param, done) {
      this.params = param;
      this.page.currentPage = 1;
      this.getList(this.page, param);
      done();
    },
    resetHandleFilter() {
      this.params = null;
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleOpenBefore(show, type) {
      show();
    },
    uploadImgBefore(file, done, loading, column){
      if(file.type === 'image/jpeg' || file.type === 'image/png'){
        done()
        return true
      }else{
        this.$message.warning('请上传JPG图片');
        loading();
        return false
      }
    },
    uploadSuccess(res) {
      this.getList(this.page);
    },
    handleClose(done) {
      done();
    },
    handleview(data, index) {
      this.$refs.crud.rowView(data, index);
    },
    changeFlagVip(is_vip, id) {
      let num;
      if (is_vip === 0) {
        num = 1;
      } else {
        num = 0;
      }
      updateFigure({ is_vip: num, id: id }).then(res => {
        this.getList(this.page);
        this.$notify.success("操作成功");
      });
    },
    changeFlagShow(show, id) {
      let num;
      if (show === 0) {
        num = 1;
      } else {
        num = 0;
      }
      updateFigure({ show: num, id: id }).then(res => {
        this.getList(this.page);
        this.$notify.success("操作成功");
      });
    },
    selectionChange(list) {
      this.selIds = (list || []).map(o => o.id).join(",");
    },
    showMany() {
      figureShowMulti({ ids: this.selIds })
        .then(() => {
          this.getList(this.page);
          this.$notify.success("操作成功");
        })
        .catch(() => {
          this.$notify.error("操作失败");
        });
    },
    handleUpdate(row, index) {
      const data = row
      const arr = []
      if(data.city){
        for (const iterator of data.city) {
          iterator = parseInt(iterator)
          arr.push(iterator)
        }
        data.city = arr
      }
      
      this.$refs.crud.rowEdit(data, index);
    },
    create(row, done, loading) {
      if(row.city){
        this.form.city = row.city.join(',')
      }
      putFigure(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify.success("创建成功");
        })
        .catch(() => {
          loading();
        });
    },
    update(row, index, done, loading) {
      if(row.city){
        this.form.city = row.city.join(',')
      }
      putFigure(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify.success("修改成功");
        })
        .catch(() => {
          loading();
        });
    },
    deletes(row) {
      this.$confirm("此操作将永久删除该人物, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteFigure({ id: row.id })
          .then(() => {
            this.getList(this.page);
            this.$notify.success("删除成功");
          })
          .catch(() => {
            this.$notify.error("删除失败");
          });
      });
    }
  }
};
</script>
<style lang="less" scoped>
  .tagBg {
    background: #aaa;
    border-radius: 5px;
    padding: 2px 4px;
    margin-right: 3px;
    color: #ffffff;
  }
</style>